package com.wechat.order.platform.interceptor;

import com.wechat.order.constant.CookieConstant;
import com.wechat.order.constant.RedisConstant;
import com.wechat.order.exception.FakeWeChatLoginException;
import com.wechat.order.exception.SellerAuthorizeException;
import com.wechat.order.util.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by zzy on 2017/12/24.
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor{

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
                           ModelAndView modelAndView) throws Exception {
        //查询cookie
        Cookie cookie= CookieUtil.get(httpServletRequest, CookieConstant.TOKEN);
        if(cookie==null){
            log.warn("[登陆效验] cookie 取不到值");
            throw new FakeWeChatLoginException();
        }
        //去redis查询
        String tokeValue=stringRedisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX,cookie.getValue()));
        if(StringUtils.isEmpty(tokeValue)){
            log.warn("[登陆效验] 找不到redis");
            throw new FakeWeChatLoginException();
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
